//
//  LDNetWorkTool.swift
//  Weibo201655
//
//  Created by pro on 16/5/5.
//  Copyright © 2016年 LeeDan. All rights reserved.
//

import UIKit
import AFNetworking

enum LDNetWorkToolError: Int {
    case AccessTokenEmpty = -1
    case UidEmpty = -2
    
    //计算形属性，不能有存储性属性
    var errorMessage: String {
        get {
            switch self {
            case .AccessTokenEmpty:
                return "access_token 没有值"
            case .UidEmpty:
                return "Uid 没有值"
            }
        }
    }
    
    //方法
    func error()->NSError {
        return NSError(domain: "cn.itcast.net", code: self.rawValue, userInfo: ["errorMessage": self.errorMessage])
    }
}

class LDNetWorkTool: AFHTTPSessionManager {

    //MARK: 单例
    class func sharedNetWorkTool()->LDNetWorkTool {
        
        return instance
    }
    
    private static let instance: LDNetWorkTool = {
        let urlStr = "https://api.weibo.com/"
        let tool = LDNetWorkTool(baseURL: NSURL(string: urlStr))
        tool.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as? Set<String>
        return tool
    }()
    
    //MARK: 私有构造函数，防止外界直接调用构造函数创建新的对象
//    private override init() {
//        super.init()
//    }
    
    //MARK: 请求  
    //App Key：1696904985
    //App Secret：a98c2fe2ffd4fcfb7007a5a063e92a7c
    //http://itcast.cn
    // MARK: - Oauth授权相关
    let client_id = "1696904985"
    let redirect_uri = "http://itcast.cn"
    let oauthUrl = "https://api.weibo.com/oauth2/authorize"
    let client_secret = "a98c2fe2ffd4fcfb7007a5a063e92a7c"
    let grant_type = "authorization_code"
    
    //MARK: 授权URL
    func oAuthURL()->NSURL {
        
        let urlStr = oauthUrl + "?" + "client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
        return NSURL(string: urlStr)!
    }
    
    //MARK: 获取Token 以及 部分用户信息
    func loadAccessToken(code: String, finished:(response: [String: AnyObject]?, error: NSError?)->()) {
        //https://api.weibo.com/oauth2/access_token
        let urlStr = "oauth2/access_token"
        let para = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": grant_type,
            "code": code,
            "redirect_uri": redirect_uri
        ]
        POST(urlStr, parameters: para, progress: nil, success: { (_, response) -> Void in
            
            let dict = response as? [String: AnyObject]
            finished(response: dict, error: nil)
            
            }) { (_, error) -> Void in
            finished(response: nil, error: error)
        }
    }
    
    //MARK: 获取用户的头像昵称等信息，完善用户信息
    func loadMoreUserAccountInfo(finished: (response: [String: AnyObject]?, error: NSError?)->()) {
        
        //可选绑定，guard判断有没有值
        guard let access_token = sharedUserAccount?.access_token else {
            print("access_token 没有值，不能请求, 无法完善用户信息")
            return
        }
        
        guard let uid = sharedUserAccount?.uid else {
            print("uid 没有值，不能请求， 无法完善用户信息")
            return
        }
        
        let para: [String: AnyObject] = [
            //从全局变量：共享用户信息sharedUserAccount中获取
            "access_token": access_token,
            "uid": uid
        ]
        
        GET("2/users/show.json", parameters: para, progress: nil, success: { (_, response) -> Void in
            
            let dict = response as! [String: AnyObject]
            finished(response: dict, error: nil)
            
            }) { (_, error) -> Void in
                finished(response: nil, error: error)
        }
        
    }

    func loadStatues(since_id: Int, max_id: Int, finished: (response: [String: AnyObject]?, error: NSError?)->()) {
        
        guard let access_token = sharedUserAccount?.access_token else {
            print("access_token 没有值，不能请求微博数据")
            return
        }
        
        
        
        let urlStr = "2/statuses/home_timeline.json"
        var para = [String: AnyObject]()
        para["access_token"] = access_token //从全局变量：共享用户信息sharedUserAccount中获取
        
        //判断是上拉还是下拉刷新
        if since_id > 0 {
            para["since_id"] = since_id
        }
        if max_id > 0 {
            para["max_id"] = max_id - 1
        }
        
        GET(urlStr, parameters: para, progress: nil, success: { (_, response) -> Void in
            let dict = response as! [String: AnyObject]
            finished(response: dict, error: nil)
            }) { (_, error) -> Void in
                finished(response: nil, error: error)
        }
        
    }
    
}
